<?php
namespace app\admin\classes;

use app\common\model\AdminUser as Model;
use app\common\model\AdminRole as RoleModel;
use core\Res;
use core\Ac;
use core\Func;

/**
 * 管理用户
 */
class AdminUser
{
  static protected $MODEL=Model::class;

  static protected $instance;
  const CACHE_KEY="User_";
  const CACHE_EXPIRE=3600;//缓存过期时间

  protected $data=[];//用户基本信息
  protected $user;//用户模型

  public $ac=false;

  private function __construct($id=""){
    if (empty($id)){
      // $this->check();
    }else{
      $this->init($id);
    }
  }
  // 防止克隆对象
  private function __clone(){}

  // 获取实例
  static function getInstance(){
    if (!static::$instance instanceof static) {
      static::$instance = new static();
    }
    return static::$instance;
  }
  static function __make(){
    return static::getInstance();
  }
  // 清理
  function clean(){
    $this->data=[];
    $this->user=false;
  }
  // 通过id获取用户信息
  function init($id){
    $this->clean();
    $this->user=self::$MODEL::get($id);
    if ($this->user){
      $this->parse_userInfo($this->user);
    }
    return $this->id();
  }
  // 处理用户信息
  function parse_userInfo($user){
    $role=$user->role;
    $role=Func::json2arr($role);

    $roles=RoleModel::where("id","in",$role)->all();
    $permission=[];
    $this->data["roleName"]=[];
    foreach ($roles as $v) {
      $this->data["roleName"][]=$v["name"];
      $permission=array_merge($permission,Func::json2arr($v["permission"]));
    }

    $permission=array_unique($permission);
    $this->ac=new AC($permission);
  }
  // 获取用户id
  function id(){
    return ($this->user)?$this->user->id:false;
  }

  // 登录
  function login($username,$password){
    $result=false;
    $this->user=self::$MODEL::get([
      'status' => 1,
      'username' => $username,
      'password' => md5($password),
      ]);
    if($this->user){
      session(self::CACHE_KEY."userid",$this->user->id);
      $result=$this->user->id;
    }else{
      $result=false;
    }


    return $result;
  }
  // 登出
  function logout(){
    session(self::CACHE_KEY."userid",null);
  }
  // 检查是否登录
  function check(){

    if (!$this->id()){
      $uid=session(self::CACHE_KEY."userid");
      if (!empty($uid)){
        $this->init($uid);
      }
    }

    return $id=$this->id();
  }
  // 获取用户信息
  function get($key){
    return $this->user->getAttr($key);
  }
  // 修改信息
  function set($key,$value){
    $this->user->allowField(true)->save([
      $key=>$value
    ]);
    return $this;
  }
  function setArr($arr){
    $this->user->allowField(true)->save($arr);
    return $this;
  }

  // 获取头像
  function headimg(){
    $img=$this->user->avatarUrl;
    if (empty($img)){
      $img="/images/user-profile.jpg";
    }else{
      $img=Res::toRes($img,0,"url");
    }
    return $img;
  }
  // 获取角色名
  function getRoleName(){
    return Func::arr2str($this->data["roleName"]);
  }


}
